package cn.itcast.orders.service.impl;


import cn.itcast.constant.MessageConstant;
import cn.itcast.context.BaseContext;
import cn.itcast.exception.BaseException;
import cn.itcast.orders.pojo.AddressBook;
import cn.itcast.orders.mapper.AddressBookMapper;
import cn.itcast.orders.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 查询当前登录用户的所有地址信息
     *
     * @return
     */
    @Override
    public List<AddressBook> list() {
        return addressBookMapper.listByUserId(BaseContext.getCurrentId());
    }

    /**
     * 新增地址
     *
     * @param addressBook
     */
    @Override
    public void addressBookResult(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> addressBooks = addressBookMapper.listByUserId(BaseContext.getCurrentId());
        addressBooks.forEach(o -> {
            if (o.equals(addressBook)) {
                //如果地址重复则添加失败
                throw new BaseException(MessageConstant.DUPLICATE_ADDRESS);
            }
        });

        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.add(addressBook);
        return;
    }

    /**
     * 根据id查询地址
     *
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Integer id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    /**
     * 根据id修改地址
     *
     * @param addressBook
     */
    @Override
    public void updateById(AddressBook addressBook) {
        addressBookMapper.update(addressBook);

        return;
    }

    /**
     * 根据id删除地址
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        addressBookMapper.deleteById(id);

        return;
    }

    /**
     * 根据地址表id设置默认地址
     *
     * @param id
     */
    @Override
    @Transactional
    public void updateDefaultAddress(Long id) {
        //将用户的所有地址设置为非默认地址
        addressBookMapper.updatesByUserId(BaseContext.getCurrentId());

        AddressBook addressBook = AddressBook.builder()
                .id(id.longValue())
                .isDefault(1)
                .build();
        addressBookMapper.update(addressBook);
    }

    /**
     * 查询默认地址
     *
     * @return
     */
    @Override
    public AddressBook getDefaultAddressByUserId() {
        AddressBook addressBook = addressBookMapper.getDefaultAddressByUserId(BaseContext.getCurrentId());

        Date date = new Date(System.currentTimeMillis());
        return addressBook;
    }


}